<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <!-- 直接按路由来就好 -->
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon
        center
      >
      </el-alert>
      <!-- 步骤条activeIndex数字型才能切换 -->
      <el-steps
        :space="200"
        :active="Number(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tap栏before-leave切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。 -->
        <el-tabs
          :tab-position="tabPosition"
          v-model="activeIndex"
          :before-leave="beforeTableleave"
          @tab-click="TabClick"
        >
          <!--type="number"文本框为数字型  -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                :options="ParentCateList"
                :props="cascaderProps"
                v-model="selectedKeys"
                clearable
                @change="handChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabledate"
              :key="item.attr_id"
            >
              <!-- 多级复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cb"
                  v-for="(cb, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2"
            ><el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabledate"
              :key="item.attr_id"
              ><el-input v-model="item.attr_vals"></el-input></el-form-item
          ></el-tab-pane>
          <el-tab-pane label="商品图片" name="3"
            ><el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="handSuccess"
              :limit="number1"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb,且不能超过3个
              </div>
            </el-upload></el-tab-pane
          >
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑框 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品 -->
            <el-button type="primary" class="imgButton" @click="Add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览弹出框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewdialogVisible"
      width="50%"
    >
      <img :src="previewPath" alt="" class="previewimg" />
    </el-dialog>
  </div>
</template>

<script>
// 拷贝组件
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      // 控制tap栏的位置
      tabPosition: 'left',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 父级分类的列表数据
      ParentCateList: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 选中的父级Id数组
      selectedKeys: [],
      // 动态参数
      manyTabledate: [],
      // 静态参数
      onlyTabledate: [],
      // 上传图片后台地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传组件的headers请求头
      headersObj: { Authorization: window.sessionStorage.getItem('token') },
      // 图片上传限制个数3个
      number1: 3,
      // 图片预览路径
      previewPath: '',
      // 图片预览弹出框显示状态
      previewdialogVisible: false,
      // 验证规则
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    this.getParentCatelist()
  },
  methods: {
    // 获取父级分类的数据列表
    async getParentCatelist () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.ParentCateList = res.data
    },
    handChange () {
      //  //  只要三级分类下的节点
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        return 0
      }
    },
    beforeTableleave (activeName, oldActiveName) {
      //  console.log("即将进入标签页名字"+activeName)
      //  console.log("即将离开标签页名字"+oldActiveName)
      if (oldActiveName === '0' && this.selectedKeys.length !== 3) {
        this.$message.error('请选择三级分类')
        return false
      }
    },
    // 激活的tab页
    async TabClick () {
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        // 访问动态参数面板
        // 根据所选分类的Id,和当前面板的参数, 获取对应的参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          { params: { sel: 'many' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败！')
        }
        res.data.forEach((item) => {
          // 通过空格分割成数组
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTabledate = res.data
        // console.log(this.manyTabledate);
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取参数列表失败！')
        }
        this.onlyTabledate = res.data
        // console.log(this.onlyTabledate);
      }
    },
    // 图片预览效果
    handlePreview (file) {
      // console.log(file);
      this.previewPath = file.response.data.url
      this.previewdialogVisible = true
    },
    // 图片移出事件
    handleRemove (file) {
      console.log(file)
      // 1.获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2.从pics数组中，找到图片对应的索引值,通过数组中的findIndex找到匹配的index
      const i = this.addForm.pics.findIndex((e) => e.pic === filePath)
      // 3.调用splice方法，移除图片信息
      this.addForm.pics.splice(i, 1)
      // console.log(this.addForm);
    },
    // 图片上传成功事件
    handSuccess (response) {
      // console.log(response);
      // 获得一个图片信息
      const picInfo = {
        pic: response.data.tmp_path
      }
      // 将图片信息添加到pics数组中
      this.addForm.pics.push(picInfo)
      // console.log(this.addForm);
    },
    // 添加商品的预验证
    Add () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 给他一个分类参数我没一开始写进addfrom
        this.addForm.goods_cat = this.selectedKeys
        // 请求添加路由
        // 发送请求前：需对提交的表单进行处理goods_cat attrs
        // this.addForm.goods_cat = this.addForm.goods_cat.join(',')
        // 以上写法不对：级联选择器绑定的对象goods_cat要求是数组对象
        // 解决办法: 包：lodash 方法（深拷贝）：cloneDeep(boj)
        // 将this.addForm进行深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTabledate.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            // 接收对象为字符串将数组分割为字符串
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态参数
        this.onlyTabledate.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            // 接收对象为字符串静态里自己已经为字符串
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        // 将处理好的参数赋值给form
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发起请求添加商品
        // 商品名称必须是唯一的
        const { data: res } = await this.$http.post('goods', form)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加商品成功!')
        // 进入商品列表
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 当前选中的3级发类Id
    cateID () {
      if (this.selectedKeys.length === 3) {
        // 选中数组的最后一项
        return this.selectedKeys[this.selectedKeys.length - 1]
      }
      return null
    }
  }
}
</script>

<style Lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-steps {
  margin-bottom: 15px;
}
.el-checkbox {
  /* 改变原来样式 */
  margin: 0 15px 0 0 !important;
}
.previewimg {
  /* 强制写入框框中 */
  width: 100%;
  height: 100%;
}
.imgButton {
  margin-top: 15px;
}
</style>
